package com.xyzwps.webfluxjava.common.exception;

import com.google.common.collect.ImmutableMap;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;

import java.io.IOException;
import java.util.Map;

/**
 * 这里声明的异常处理器只能处理 Annotated Controllers 抛出的异常。
 * <p>
 * Functional Endpoints 抛出的异常直接由 {@link DefaultErrorWebExceptionHandler} 接管。
 */
@ControllerAdvice
public class ExceptionHandlers {

    @ExceptionHandler
    public ResponseEntity<Map<String, Object>> handleBizException(IOException ex) {
        return new ResponseEntity<>(ImmutableMap.of(
                "routerType", "traditional",
                "errorMessage", ex.getMessage(),
                "helloWorld", "你知道，这只是一个胡乱来的示例"
        ), HttpStatus.GONE);
    }

    @ExceptionHandler
    public ResponseEntity<Map<String, Object>> handleBizException(BizException ex) {
        return new ResponseEntity<>(ImmutableMap.of(
                "routerType", "traditional",
                "errorMessage", ex.getMessage()
        ), ex.getStatus());
    }

    /**
     * 这里如果不兜住所以异常，异常就会被 {@link DefaultErrorWebExceptionHandler} 处理。
     */
    @ExceptionHandler
    public ResponseEntity<Map<String, Object>> handleBizException(Exception ex) {
        return new ResponseEntity<>(ImmutableMap.of(
                "routerType", "traditional",
                "errorMessage", ex.getMessage()
        ), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
